package handlers

import (
	"encoding/json"
	"log/slog"

	"lsp-server/internal/protocol"
)

const DidChangeTextDocumentNotification = "textDocument/didChange"

type DidChange struct {
	documentUpdates chan protocol.TextDocumentItem
}

func NewDidChange(documentUpdates chan protocol.TextDocumentItem) *DidChange {
	return &DidChange{documentUpdates: documentUpdates}
}

func (d DidChange) Call(params json.RawMessage) error {
	slog.Info("received didChange notification")
	changeParams, err := d.parseParams(params)
	if err != nil {
		slog.Error("Error to parse didChange params")
		return err
	}
	slog.Debug("didChange params", slog.Any("params", *changeParams))

	d.documentUpdates <- protocol.TextDocumentItem{
		URI:     changeParams.TextDocument.URI,
		Version: changeParams.TextDocument.Version,
		Text:    changeParams.ContentChanges[0].Text,
	}

	return nil
}

func (d DidChange) parseParams(params json.RawMessage) (*protocol.DidChangeTextDocumentParams, error) {
	var changeParams protocol.DidChangeTextDocumentParams
	if err := json.Unmarshal(params, &changeParams); err != nil {
		return nil, err
	}

	return &changeParams, nil
}
